package com.buvaka;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

import com.buvaka.features.Features;

public class UpdateCategoriesFile {
	static final String VAR_CATEGORIES = "var categories = ";
	public static void update (MongoClient client) {
		try (FileOutputStream fout = new FileOutputStream( "src/main/webapp/js/categories.js" )){
			MongoClient mongo = client;
            DB db = mongo.getDB("gis");
            DBCollection categories = db.getCollection("categories");
            DBCursor allCategories = categories.find();
            FileChannel fc2 = fout.getChannel();
                  
               
            StringBuilder str = new StringBuilder(VAR_CATEGORIES).append(Features.OPEN);
            
            while (allCategories.hasNext()) {
            	DBObject current = allCategories.next();
            	str.append("\"").append(current.get("_id")).append("\":\"").append(current.get("picture")).append("\"").append(Features.COMMA);
            		
            }
            
            str.setLength(str.length() - 2); //remove comma + space at the end
            
            str.append(Features.CLOSE).append(";");
            fc2.write(ByteBuffer.wrap(str.toString().getBytes("UTF-8")));            
            
            
		} catch (IOException e) {
            e.printStackTrace();
        }
	}
	
	
	public static void main (String args[]) throws Exception{
		update(new MongoClient());
	}

}
